/**
 * Created by cuihongquan on 2015/7/6.
 * based on ztree, jqueryUI
 */
$.widget('summer.org', {
    version: '1.0',
    options: {
        'selectedMulti': true,
        'event': 'keyup',
        'url': '',
        'idKey': 'oid',
        'pIdKey': 'pid',
        'rootId': '',
        'height': 450,
        'width': 600,
        'textName': '组织机构',
        'textInput':true
    },
    //ztree的主要的配置
    _zTreeSettings: function () {
        var that = this;
        that._settings = {
            data: {
                simpleData: {
                    enable: true,
                    idKey: that.options.idKey,
                    pIdKey: that.options.pIdKey
                }
            },
            check: {
                enable: that.options.selectedMulti,
                chkStyle: "checkbox",
                radioType: 'all',
                chkboxType: { "Y": "s", "N": "s" },
                autoCheckTrigger: true
            },
            view: {
                selectedMulti: that.options.selectedMulti
            },
            callback: {
                onClick: function (e, treeId, node) {
                    that._zTreeOnClick(e, treeId, node);
                },
                onCheck: function (e, treeId, node) {
                    that._zTreeOnCheck(e, treeId, node);
                }
            }
        };
    },
    _create: function () {
        //构造组织机构树
        this._createOrg();
        //加载数据
        this._loadData();
        //ztree的配置
        this._zTreeSettings();
        //绑定事件
        this._bindEvents();
    },
    destroy: function () {
        var ele = this.element,
            id = ele.attr('id'),
            $win = $('#' + id + 'Container'),
            $input = $win.find('.summer-org-search-input');
        //input
        ele.off();
        //search
        $input.off();
        //关闭方法
        $win.find('.summer-window-close').off();
        //添加按钮
        $win.find('.summer-org-plus').off();
        //定义节点删除事件
        $win.find('.summer-org-selected-con').off();
        //删除dom
        $win.remove();
        //删除隐藏域
        $('#summer-org-'+id+'-data').remove();
        $('#'+id+'-hidden').remove();
    },

    //构建组织机构dom节点
    _createOrg: function () {
        var that = this,
            ele = this.element,
            id = ele.attr('id');
        //构建input隐藏域
        ele.after('<input type="hidden" id="' + id + '-hidden" value="" name="' + ele.attr('name') +
            '"><input type="hidden" id="summer-org-'+id+'-data">');
        //修改当前的input属性值
        ele.removeAttr('name');
        //构建window窗口里面的容器
        var $win = $('#' + id + 'Container');
        if ($win.length == 0) $(ele).closest('body').append('<div id="' + id + 'Container" class="summer-org-container"></div>');
        $win = $('#' + id + 'Container');
        if (that.options.textInput) {
        	$win.append(
                //遮罩层
                '<div class="summer-window-mask" style="display: none"></div>' +
                //主容器
                '<div class="summer-window-container" style="width:' + that.options.width + 'px;height:' +
                that.options.height + 'px;left:50%;top:50%;margin-left:-' + that.options.width / 2 + 'px;' +
                'margin-top:-' + that.options.height / 2 + 'px;z-index:9999999;background-color:#ffffff;">' +
                //容器头
                '<div class="summer-window-header"><div class="summer-window-title"><i class="fa fa-laptop"></i>' +
                that.options.textName + '</div><a class="summer-window-close" href="javascript:;"><i class="icon icon-wrong"></i></a></div>' +
                //容器内容
                '<div class="summer-window-body" style="width: 100%;height: 90%;">' +
                '<div class="summer-org"><div class="summer-org-search">' +
                that.options.textName + '<input type="text" class="summer-input summer-org-search-input"></div>' +
                '<div class="summer-org-treebox"><ul class="ztree" id="summer-org-tree-' + id + '"></ul></div>' +
                '<div class="summer-org-selected-con"></div></div></div>');
        } else {
        	$win.append(
                //遮罩层
                '<div class="summer-window-mask" style="display: none"></div>' +
                //主容器
                '<div class="summer-window-container" style="width:' + that.options.width + 'px;height:' +
                that.options.height + 'px;left:50%;top:50%;margin-left:-' + that.options.width / 2 + 'px;' +
                'margin-top:-' + that.options.height / 2 + 'px;z-index:9999999;background-color:#ffffff;">' +
                //容器头
                '<div class="summer-window-header"><div class="summer-window-title"><i class="fa fa-laptop"></i>' +
                that.options.textName + '</div><a class="summer-window-close" href="javascript:;"><i class="icon icon-wrong"></i></a></div>' +
                //容器内容
                '<div class="summer-window-body" style="width: 100%;height: 90%;">' +
                '<div class="summer-org">' +
                '<div class="summer-org-treebox" style="top: 10px;"><ul class="ztree" id="summer-org-tree-' + id + '"></ul></div>' +
                '<div class="summer-org-selected-con"></div></div></div>');
        }
        
        $win.find('.summer-org').after(
                '<div class="summer-org-plus">' +
                '<a class="btn btn-primary btn-large" ' +
                'href="javascript:;" class="summer-org-btn-plus"><span class="btn-i">' +
                '<i class="icon icon-plus icon-white"></i></span>' +
                '<span class="btn-word">添加</span></a></div>');
        if (that.options.selectedMulti) {
            //重新进行布局
            $win.find('.summer-org-treebox').css('bottom', '120px');
        } else {
        	$win.find('.summer-org-treebox').css('bottom', '50px');
            $win.find('.summer-org-selected-con').hide();
        }
    },

    //加载数据
    _loadData: function () {
        var that = this;
        $.ajax({
            type: 'POST',
            data: {
                'id': that.options.rootId
            },
            async: true,
            url: that.options.url,
            success: function (data) {
                if (data.result === 'success' && data.data.length) {
                    var list = data.data;
                    window.localStorage.zzjg = JSON.stringify(list);
                    that._tree = $.fn.zTree.init($("#summer-org-tree-" + that.element.attr('id')), that._settings, list);
                    //展开一级节点
                    var nodes = that._tree.getNodes();
                    that._tree.expandNode(nodes[0], true, false, true);
                }
            }
        });
    },

    //绑定事件
    _bindEvents: function () {
        var that = this,
            ele = this.element,
            id = ele.attr('id'),
            $win = $('#' + id + 'Container'),
            $input = $win.find('.summer-org-search-input'),
            $con = $win.find('.summer-org-selected-con'),
            $item,
            ids = [],
            names = [];

        //input框点击事件
        ele.on('click', null, function () {
            that._showWin($win);
            if (!that.options.selectedMulti) {
            	that._tree.selectNode(that._tree.getNodeByParam(that._settings.data.simpleData.idKey, $('#'+id+'-hidden').val(), null));
            }
        });

        //查询框的事件
        $input.on(that.options.event, null, function () {
            var nodes = that._tree.getNodesByFilter(
                //过滤方法
                function (node) {
                    var val = $win.find('.summer-org-search-input').val().replace(/(^\s*)|(\s*$)/g, '');
                    return (val && node.name.match(val));
                }, false);
            if (that.options.selectedMulti) {
                //取得这个node集合
                if (nodes.length) {
                    that._tree.selectNode(nodes[0]);
                    that._zTreeOnClick(null, null, nodes[0]);
                }
            } else {
                if (nodes.length) that._tree.selectNode(nodes[0]);
            }
        });

        //关闭方法
        $win.find('.summer-window-close').on('click', null, function () {
            that._closeWin($win);
        });

        //添加按钮
        $win.find('.summer-org-plus').on('click', null, function () {
            $item = $con.find('.summer-org-selected-item');
            ids = [];
            names= [];
            $.each($item, function (index, item) {
                ids.push(item.id);
                names.push($(item).text());
            });
            //清空内容
            that._resetInput();
        	that._setValues(that,ids.join(),names.join());
        });

        //定义节点删除事件
        $con.on('click', '.summer-org-selected-item', function () {
                var node = that._tree.getNodeByParam(that._settings.data.simpleData.idKey, $(this).attr('id'), null);
            $(this).remove();
            that._tree.checkNode(node, false, false);
        });
    },

    //树的check事件
    _zTreeOnCheck: function (e, treeId, node) {
        var that = this,
            ele = that.element,
            $win = $('#' + ele.attr('id') + 'Container'),
            $con = $win.find('.summer-org-selected-con'),
            $item = $con.find('.summer-org-selected-item'),
            flag = true;
        $.each($item, function (index, item) {
            if (item.id === node[that._settings.data.simpleData.idKey]) {
                flag = false;
            }
        });
        if (flag) {
            $con.append('<span class="summer-org-selected-item" id="' + node[that._settings.data.simpleData.idKey] +
                '">' + node.name + '<span class="icon icon-wrong"></span></span>');
        }
        //如果没有checked
        if (!node.checked) {
            $('#' + node[that._settings.data.simpleData.idKey]).remove();
        }
    },

    //树的点击事件
    _zTreeOnClick: function (e, treeId, node) {
        var that = this,
            ele = that.element,
            id= ele.attr('id'),
            $win = $('#' + id + 'Container'),
            $con = $win.find('.summer-org-selected-con'),
            $item = $con.find('.summer-org-selected-item'),
            flag = true;
            //点击事件同时事添加check
            that._tree.checkNode(node, true, false);
            //如果存在数据
            $.each($item, function (index, item) {
                if (item.id === node[that._settings.data.simpleData.idKey]) {
                    flag = false;
                }
            });
            if (flag) {
            	if(that.options.selectedMulti){
            		$con.append('<span class="summer-org-selected-item" id="' + node[that._settings.data.simpleData.idKey] +
                            '">' + node.name + '<span class="icon icon-wrong"></span></span>');
            	}else{
            		$con.empty().append('<span class="summer-org-selected-item" id="' + node[that._settings.data.simpleData.idKey] +
                            '">' + node.name + '<span class="icon icon-wrong"></span></span>');
            	}
                
            }
    },

    //窗口关闭事件
    _closeWin: function ($win) {
        $win.find('.summer-window-mask').hide();
        $win.find('.summer-window-container').removeClass('transition-in');
    },

    //窗口打开事件
    _showWin: function ($win) {
        $win.find('.summer-window-mask').show();
        $win.find('.summer-window-container').addClass('transition-in');
    },

    //赋值方法
    _setValues :function(that,ids,names){
        var ele = that.element,
            id = ele.attr('id');
        $('#summer-org-'+id+'-data').attr({
            'data-ids':ids,
            'data-names':names
        });
        $('#'+id+'-hidden').val(ids);
        that._closeWin($('#' + id + 'Container'));
        ele.val(names);
    },
    //赋值方法 接字符串
    setValues:function(ids){
    	var that = this,
    		opts = that.options,
    		idsArr = ids.split(',');
    		nodeList = [],
    		names=[];
		if(window.localStorage.zzjg){
			nodeList = JSON.parse(window.localStorage.zzjg);
		}else{
			$.error('window.localStorage.zzjg is empty!!');
		}
		$.each(idsArr,function(index,value){
			$.each(nodeList,function(j,w){
				if(value == w[opts.idKey]){
					names.push(w.name);
				}
			});
		});
		//调用私有的方法
		that._setValues(that,ids,names);
    },

    //重置方法
    _resetInput: function () {
        var that = this,
            ele = that.element,
            id = ele.attr('id');
        $('#summer-org-'+id+'-data').attr({
            'data-ids':'',
            'data-names':''
        });
        $('#'+id+'-hidden').val('');
        ele.val('');
        $('#'+id+'Container').find('.summer-org-selected-con').empty();
    }
});